package chapter15;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/2/23 11:34
 */
class Producer extends Thread {
    MyBlockingQueue<String> queue;

    public Producer(MyBlockingQueue<String> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        int num = 0;
        try {
            while (true) {
                String task = String.valueOf(num);
                queue.put(task);
                System.out.println(Thread.currentThread().getName() + " produce task " + task);
                num++;
                TimeUnit.SECONDS.sleep(new Random(5).nextInt());
            }
        } catch (InterruptedException e) {
            System.out.println(Thread.currentThread().getName() + "exit via interrupt");
        }
    }
}

class Conusmer extends Thread {
    MyBlockingQueue<String> queue;

    public Conusmer(MyBlockingQueue<String> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        try {
            while (true) {
                String task = queue.take();
                System.out.println(Thread.currentThread().getName() + " handle task " + task);
                TimeUnit.SECONDS.sleep(new Random(8).nextInt());
            }
        } catch (InterruptedException e) {
            System.out.println(Thread.currentThread().getName() + "exit via interrupt");
        }
    }
}

public class QueueTest {
    public static void main(String[] args) throws InterruptedException {
        MyBlockingQueue<String> queue = new MyBlockingQueue<>(10);
        Thread producer = new Producer(queue);
        producer.setName("producer");

        Thread consumer0 = new Conusmer(queue);
        consumer0.setName("consumer-0");
        Thread consuemr1 = new Conusmer(queue);
        consuemr1.setName("consumer-1");

        ExecutorService exec = Executors.newFixedThreadPool(5);
        exec.submit(producer);
        exec.submit(consuemr1);
        exec.submit(consumer0);

        TimeUnit.SECONDS.sleep(30);
        exec.shutdownNow();
    }
}
